import 'package:get/get.dart';
import 'package:xin_he/page/login/xin_he_login_action.dart';

import '../../../service/xin_he_reqest.dart';
import '../../../utils/xin_he_toast.dart';
import '../model/xin_he_user_info_entity.dart';
import 'xin_he_login_state.dart';

class XinHeLoginLogic extends GetxController {
  final XinHeLoginState state = XinHeLoginState();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
  }

  /// 回收键盘
  void keyboardBack() {
    if (Get.focusScope?.hasPrimaryFocus == true) {
      Get.focusScope?.unfocus();
    }
  }

  void onPWChange(String pw) {
    state.pw = pw;
    setSaveButtonStatus();
  }

  void onPhoneChange(String phone) {
    state.phone = phone;
    setSaveButtonStatus();
  }


  ///设置状态
  setSaveButtonStatus() {
    if (state.pw.length < 8 || state.phone.length != (11 + 2) ||
        !state.selected.value) {
      state.saveEnable.value = false;
    } else {
      state.saveEnable.value = true;
    }
  }


  ///登录操作
  Future<bool> userLogin() async {
    if (state.phone.length == 0) {
      XinHeToast.center('请输入手机号');
      return true;
    }
    if (state.phone.length != (11 + 2)) {
      XinHeToast.center('请输入11位手机号');
      return true;
    }
    if (!GetUtils.isPhoneNumber(state.phone.replaceAll(' ', ''))) {
      XinHeToast.center('手机号格式错误!');
      return true;
    }

    // if (state.pw.length < 8 || state.pw.length > 16) {
    //   XinHeToast.center('密码需要8-16位组合');
    //   return true;
    // }

    Map<String, dynamic> params = {
      "phone": state.phone.replaceAll(' ', ''),
      'password': state.pw,
      'countryCode': '+86'
    };

    Map<String,dynamic>map = {
      'mobile':state.phone.replaceAll(' ', ''),
      'password':'123456',
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/member/appLogin',params: map,isPost: false);

    if(!result.result){
      XinHeToast.center('请求失败，请稍后再试');

      return false;
    }
    if(result.data['code'] == 0){
      XinHeToast.center('登录成功');

      String token = result.data['data']['token'];
      Map<String, dynamic> data = result.data['data']['member'];
      XinHeUserInfoEntity model = XinHeUserInfoEntity.fromJson(data);
      XinHeLoginAction.loginSucSetData(result.data['data']);
      Get.back();
    }else {
      XinHeToast.center(result.data['message'] ??'');
      return false;

    }


    return true;
  }

}
